package inicio;

import java.net.*;
import java.io.*;
import java.sql.*;
import java.util.Scanner;

@SuppressWarnings("unused")
public class ThreadEscucha extends Thread {
	private Socket s;
	private ConnectionManager cm;
	private Mensaje to;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;

	public ThreadEscucha(Socket so) {
		try {
			s = so;
			ois = new ObjectInputStream(s.getInputStream());
			oos = new ObjectOutputStream(s.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() {
		try {
			do {
				Object aux = ois.readObject();
				if (aux != null && aux instanceof Mensaje) {
					to = (Mensaje) aux;
					if (to.getId() == 1) {
						this.consultaInicioSesion();
					} else if (to.getId() == 2) {
						this.registroNuevoJugador();
					}
				}
				Thread.sleep(20);
			} while (to.getId() != -1);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				oos.close();
				ois.close();
				s.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void consultaInicioSesion() {
		try {

			cm = new ConnectionManager();
			PreparedStatement pstm = cm.getConn().prepareStatement(
					"Select * from Jugador where nick = ?");
			String aux[] = to.getMsg().split(" ");
			pstm.setString(1, aux[0]);
			ResultSet rs = pstm.executeQuery();
			Jugador j = new Jugador();
			if (rs.next()) {

				j.setApyn(rs.getString("apyn"));
				j.setDni(rs.getInt("dni"));
				j.setNick(rs.getString("nick"));
				j.setGanadas(rs.getInt("ganadas"));
				j.setPerdidas(rs.getInt("perdidas"));
				j.setPass(rs.getString("password"));
				if (j.getPass().equals(aux[1])) {
					oos.writeObject(j);
				} else {
					j.setNick(null);
					oos.writeObject(j);
				}
			} else {
				j.setNick(null);
				oos.writeObject(j);
			}
			oos.flush();
			pstm.close();
			cm.Desconectar();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}

	public void registroNuevoJugador() {
		try {
			cm = new ConnectionManager();
			String datos[] = to.getMsg().split(" ");
			PreparedStatement pstm = cm
					.getConn()
					.prepareStatement(
							"Insert into Jugador(apyn,nick,dni,password) values(?, ?, ?, ?)");
			pstm.setString(1, datos[0].replace("_", " ").replace("?", ""));
			pstm.setString(2, datos[1]);
			pstm.setInt(3, Integer.parseInt(datos[2]));
			pstm.setString(4, datos[3]);
			pstm.execute();
			pstm.close();
			cm.Desconectar();
			to.setId(1);
			to.setMsg(null);
			oos.writeObject(to);
			oos.flush();
		} catch (Exception e) {
			try {
				to.setId(-1);
				to.setMsg(null);
				oos.writeObject(to);
				oos.flush();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
